package cn.hd01.web.controller;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.common.BaseConstant;
import cn.hd01.common.BaseConstant.CustomerType;
import cn.hd01.common.BaseConstant.RebateSummaryType;
import cn.hd01.common.BaseConstant.RoleId;
import cn.hd01.common.BaseConstant.backendType;
import cn.hd01.repository.entity.RebateSummary;
import cn.hd01.repository.entity.Role;
import cn.hd01.repository.entity.User;
import cn.hd01.service.CustomerService;
import cn.hd01.service.RebateSummaryService;
import cn.hd01.service.RoleService;
import cn.hd01.service.UserService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebConstant;
import cn.hd01.web.util.WebException;
import cn.hd01.web.util.WebHelper;

@Controller
@RequestMapping("/user")
@Auth
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private RebateSummaryService rebateSummaryService;
	
	@RequestMapping(path = {"/", ""}, method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest req) {
		
		
		Integer type = req.getParameter("type") == null ? null : Integer.valueOf(req.getParameter("type"));
		if(BaseConstant.backendType.TEACHER.equals(type)){
			m.addAttribute("teacherRoleId", RoleId.TEACHER_ROLE_ID);
			return "teacher";
		}
		
		m.addAttribute("roles", roleService.findAll());
		m.addAttribute("types", backendType.getTypeList());
		return "user";
	}
	
	@RequestMapping(path = "/detail/{id}", method = RequestMethod.GET)
	private String detail(@PathVariable("id") Integer id, Model m, HttpServletRequest req) {
		
		User loginUser = (User) req.getSession().getAttribute(WebConstant.USER_SESSION_NAME);
		if(id == null && backendType.TEACHER.equals(loginUser.getType())){
			id = loginUser.getId();
		}
		
		User teacher = userService.findOne(id);
		m.addAttribute("servant", teacher);
		return "teacherDetail";
	}
	
	@ResponseBody
	@RequestMapping(path = "/modifyPwd", method = RequestMethod.POST)
	public void modify(String oldPwd, String newPwd) {
		User u = userService.findOne(WebHelper.currentUser().getId());
		if (!u.getPassword().equals(oldPwd)) {
			throw new WebException(HttpStatus.NOT_ACCEPTABLE, "原密码错误");
		}
		userService.updatePassword(u.getId(), newPwd);
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<User> find(User u, @PageableDefault Pageable pageable) {
		Page<User> result = userService.findAdmin(u, pageable);
		
		if(backendType.TEACHER.equals(u.getType())){
			for(User user : result){
				RebateSummary rs = rebateSummaryService.findByRefIdAndType(user.getId(), RebateSummaryType.SERVANT_TEACHER);
				if(rs != null){
					user.setAllRebate(rs.getAllRebate());
					user.setAllWithdrawRebate(rs.getAllWithdrawRebate());
				}else{
					user.setAllRebate(BigDecimal.ZERO);
					user.setAllWithdrawRebate(BigDecimal.ZERO);
				}
			}
		}
		
		return result;
	}

	@ResponseBody
	@RequestMapping(path = "/resetPwd/{id}", method = RequestMethod.GET)
	private String resetPwd(@PathVariable("id") Integer id) {
		if (!userService.exists(id)) {
			throw new WebException(HttpStatus.NOT_ACCEPTABLE, "不存在该用户");
		}
		userService.updatePassword(id, WebConstant.DEFAULT_PASSWORD);
		return WebConstant.DEFAULT_PASSWORD;
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		userService.delete(id);
		customerService.updateCustomerServant(id, CustomerType.DISTRIBUTOR);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(User u) {

		Role role = roleService.findOne(u.getRoleId());
		u.setRoleName(role.getName());

		if (u.getId() == null) {
			if (userService.exists(u.getName())) {
				throw new WebException(HttpStatus.BAD_REQUEST, "用户名已经存在");
			}

			u.setPassword(WebConstant.DEFAULT_PASSWORD);
			userService.save(u);
			return;
		}

		userService.updateUser(u);
	}
}
